/**
 * title: 填写管理员代理人信息
 */
import React, { Component } from 'react';
import { Form, message, Button, Row, Col } from 'antd';
import EditBox from './components/EditBox';
import Wrapper from './components/Wrapper';
import AuthenticationForm from './components/Authentication';
import Actions from './components/Actions';
import getFileId from '@/utils/getFileId';
import { OssUpload } from 'scd';
import styles from './styles.less';
import { connect } from 'dva';

const FormItem = Form.Item;

const authStatusComponent = [
  {
    title: '您的账号尚未实名认证过 ,请先实名认证.',
    component: <AuthenticationForm />,
  },
  {
    title: '您的账号正处于实名认证审核阶段.',
    component: null,
  },
  {
    title: '您的账号已实名认证.',
    component: null,
  },
  {
    title: '您的账号实名认证失败，请重新认证.',
    component: <AuthenticationForm />,
  },
];
@Form.create()
@connect(
  ({
    loading: {
      models: { createCompany },
    },
    createCompany: { companyInformation },
    user: { info },
  }) => ({
    loading: !!createCompany,
    userInfo: info,
    companyInformation,
  })
)
class AgentInformation extends Component {
  componentDidMount() {
    const {
      location: {
        query: { temId },
      },
      dispatch,
    } = this.props;
    if (temId) {
      dispatch({
        type: 'createCompany/queryForm',
        payload: {
          temId,
          step: 3,
        },
      }).catch(errMsg => {
        message.error(errMsg);
      });
    }
    dispatch({
      type: 'user/getUserInfo',
    });
  }

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  handleSubmit = type => e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      history,
      location: {
        query: { temId },
      },
    } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        // console.log('Received values of form: ', fieldsValue);
        let values = {
          ...fieldsValue,
        };

        if (temId) values.id = temId;

        // authorizationId: oss 保存图片的id
        values.authorizationId = getFileId(fieldsValue.authorizationId);

        dispatch({
          type: `createCompany/saveForm`,
          payload: values,
        })
          .then(() => {
            message.success('保存成功');
            if (type === 'submit') {
              dispatch({
                type: `createCompany/submitForm`,
                payload: {
                  applyType: 0,
                  companyId: temId,
                },
              })
                .then(() => {
                  // message.success('操作成功');
                  history.push(`/createCompany/Result`);
                })
                .catch(errMsg => {
                  message.error(errMsg);
                });
            }
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };

  goBack = () => {
    const { dispatch, history } = this.props;
    dispatch({
      type: 'createCompany/removeLocalForm',
    });
    history.goBack();
  };

  render() {
    const {
      userInfo,
      form: { getFieldDecorator, getFieldValue },
      companyInformation,
      dispatch,
      loading,
      location: {
        query: { temId },
      },
    } = this.props;

    return (
      <Wrapper
        current={2}
        loading={loading}
        actions={
          <Actions
            temId={temId}
            dispatch={dispatch}
            goBack={this.goBack}
            handleSave={this.handleSubmit('save')}
            handleSubmit={this.handleSubmit('submit')}
          />
        }
      >
        <EditBox title="管理员实名认证（必填）" description={' '}>
          <p className={styles.agentInformationPTitle}>实名认证:</p>
          <p className={styles.agentInformationPDescription}>
            {authStatusComponent[userInfo.status || 0].title}
          </p>
          <p className={styles.agentInformationPActions}>
            {authStatusComponent[userInfo.status || 0].component}
          </p>
          <p className={styles.agentInformationPTitle}>授权书:</p>
          <p className={styles.agentInformationPDescription}>
            如果管理员不是公司法人代表. 所以请下载授权书,请公司法人代表签名并盖公司公章后上传.
          </p>

          <Form onSubmit={this.handleSubmit}>
            <div className={styles.agentInformationPActions}>
              <Row>
                <Col span={4}>
                  <Button>下载授权书模版</Button>
                </Col>
                <Col span={8}>
                  <FormItem>
                    {getFieldDecorator('authorizationId', {
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                      initialValue: companyInformation.authorizationId,
                      rules: [
                        {
                          required: true,
                          message: '请上传授权书',
                        },
                      ],
                    })(
                      <OssUpload
                        data={{
                          businessId: 0,
                          businessType: 'string',
                          companyId: 0,
                          digestMethod: 1,
                          ext: '',
                          moduleCode: 'company',
                          productLineId: 0,
                          userId: 1,
                        }}
                      >
                        {getFieldValue('authorizationId') &&
                        getFieldValue('authorizationId').length === 1 ? null : (
                          <Button type="primary">上传</Button>
                        )}
                      </OssUpload>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </div>
          </Form>
        </EditBox>
      </Wrapper>
    );
  }
}

export default AgentInformation;
